const express = require("express");
const db = require("../db/index");
const router = express.Router();

const multer = require('multer')
const path = require("path")


// 配置mutler的池
let storage = multer.diskStorage({
    // 把图片放在那里
    destination: function (req, file, cb) {
        // NodeJS的两个全局变量
        // console.log(__dirname);  //获取当前文件在服务器上的完整目录 
        // console.log(__filename); //获取当前文件在服务器上的完整路径 
        cb(null, path.join(__dirname, "../static/image"))
    },
    // 改变图片的名字
    filename: function (req, file, cb) {
        cb(null, Date.now() + path.extname(file.originalname))
    }

})

const image = multer({ storage: storage })

router.post("/upload", image.single("avator"), (req, res) => {
    
    if (req.file) {
        let tableName = req.body.tableName
        let imgType = req.file.filename
        let sql = `insert into ${tableName} set imgUrl = ?`;
        // console.log(sql,tableName)
        let p = new Promise((resolve, reject) => {
            db.query(sql, imgType, (err, result) => {
                if (err) return reject(err)
                if(result.affectedRows==1)return resolve("成功")
            })
        })
        p.then(r=>{
            res.send({
                status: 200,
                message: r,
                data: req.file.filename
            })
        },v=>{
            res.send({
                status: 401,
                message: v,
              
            })
        })
    } else {
        res.send({
            status: 401,
            message: '上传失败',
        })
    }
})

module.exports = router
